#!/bin/bash
# ========================================
# 后端部署脚本
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目路径配置
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(cd "$SCRIPT_DIR/.." && pwd)

# 应用配置
APP_NAME="ruoyi-admin.jar"
APP_PORT=8080
BACKUP_DIR="/backup/ruoyi-backend"

# JVM参数
JVM_OPTS="-Dname=$APP_NAME -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_message "$RED" "❌ 错误: $1 未安装，请先安装"
        exit 1
    fi
}

# 检查依赖
check_dependencies() {
    print_message "$BLUE" "📦 检查依赖..."
    check_command java
    check_command mvn
    
    # 检查Java版本
    JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F. '{print $1}')
    if [ "$JAVA_VERSION" -lt 8 ]; then
        print_message "$RED" "❌ 错误: Java版本必须 >= 8"
        exit 1
    fi
    
    print_message "$GREEN" "✅ Java版本: $(java -version 2>&1 | head -n 1)"
    print_message "$GREEN" "✅ Maven版本: $(mvn -version | head -n 1)"
}

# 停止旧服务
stop_old_service() {
    print_message "$BLUE" "🛑 停止旧服务..."
    
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    
    if [ -n "$PID" ]; then
        print_message "$YELLOW" "发现运行中的服务 (PID: $PID)，正在停止..."
        kill -15 $PID
        
        # 等待进程结束
        for i in {1..30}; do
            if ! ps -p $PID > /dev/null 2>&1; then
                print_message "$GREEN" "✅ 服务已停止"
                return
            fi
            sleep 1
        done
        
        # 强制结束
        print_message "$YELLOW" "⚠️  强制停止服务..."
        kill -9 $PID
        print_message "$GREEN" "✅ 服务已强制停止"
    else
        print_message "$GREEN" "✅ 没有运行中的服务"
    fi
}

# 备份旧版本
backup_old_version() {
    if [ -f "$PROJECT_ROOT/$APP_NAME" ]; then
        print_message "$BLUE" "💾 备份旧版本..."
        mkdir -p "$BACKUP_DIR"
        BACKUP_FILE="$BACKUP_DIR/$APP_NAME-$(date +%Y%m%d_%H%M%S)"
        cp "$PROJECT_ROOT/$APP_NAME" "$BACKUP_FILE"
        print_message "$GREEN" "✅ 备份完成: $BACKUP_FILE"
    fi
}

# 清理Maven缓存
clean_maven() {
    print_message "$BLUE" "🧹 清理Maven项目..."
    cd "$PROJECT_ROOT"
    mvn clean
    print_message "$GREEN" "✅ 清理完成"
}

# 编译打包
build_project() {
    print_message "$BLUE" "🔨 开始编译打包..."
    cd "$PROJECT_ROOT"
    
    # Maven打包，跳过测试
    mvn package -DskipTests
    
    # 检查打包结果
    JAR_FILE="$PROJECT_ROOT/ruoyi-admin/target/$APP_NAME"
    if [ ! -f "$JAR_FILE" ]; then
        print_message "$RED" "❌ 打包失败: 找不到 $JAR_FILE"
        exit 1
    fi
    
    # 复制到项目根目录
    cp "$JAR_FILE" "$PROJECT_ROOT/$APP_NAME"
    
    print_message "$GREEN" "✅ 打包完成: $PROJECT_ROOT/$APP_NAME"
}

# 启动服务
start_service() {
    print_message "$BLUE" "🚀 启动服务..."
    
    cd "$PROJECT_ROOT"
    
    # 创建日志目录
    mkdir -p logs
    
    # 后台启动服务
    LOG_FILE="$PROJECT_ROOT/logs/$APP_NAME.log"
    nohup java $JVM_OPTS -jar $APP_NAME > "$LOG_FILE" 2>&1 &
    
    PID=$!
    print_message "$GREEN" "✅ 服务已启动 (PID: $PID)"
    print_message "$BLUE" "📝 日志文件: $LOG_FILE"
}

# 等待服务启动
wait_for_service() {
    print_message "$BLUE" "⏳ 等待服务启动..."
    
    for i in {1..60}; do
        if curl -s http://localhost:$APP_PORT > /dev/null 2>&1; then
            print_message "$GREEN" "✅ 服务启动成功！"
            return 0
        fi
        echo -n "."
        sleep 2
    done
    
    print_message "$RED" "\n❌ 服务启动超时，请检查日志"
    print_message "$YELLOW" "查看日志: tail -f $PROJECT_ROOT/logs/$APP_NAME.log"
    exit 1
}

# 查看日志
view_logs() {
    LOG_FILE="$PROJECT_ROOT/logs/$APP_NAME.log"
    if [ -f "$LOG_FILE" ]; then
        print_message "$BLUE" "\n📋 最近日志 (最后50行):"
        echo "========================================="
        tail -n 50 "$LOG_FILE"
        echo "========================================="
        print_message "$YELLOW" "\n查看实时日志: tail -f $LOG_FILE"
    fi
}

# 显示服务信息
show_info() {
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    
    print_message "$GREEN" "\n========================================="
    print_message "$GREEN" "🎉 后端部署完成！"
    print_message "$GREEN" "========================================="
    echo ""
    print_message "$BLUE" "📂 项目目录: $PROJECT_ROOT"
    print_message "$BLUE" "📦 应用文件: $APP_NAME"
    print_message "$BLUE" "🔢 进程ID: $PID"
    print_message "$BLUE" "🌐 服务地址: http://localhost:$APP_PORT"
    print_message "$BLUE" "📝 日志目录: $PROJECT_ROOT/logs"
    echo ""
    print_message "$YELLOW" "管理命令："
    print_message "$YELLOW" "  启动: ./ry.sh start"
    print_message "$YELLOW" "  停止: ./ry.sh stop"
    print_message "$YELLOW" "  重启: ./ry.sh restart"
    print_message "$YELLOW" "  状态: ./ry.sh status"
    echo ""
}

# 检查服务状态
check_status() {
    print_message "$BLUE" "🔍 检查服务状态..."
    
    PID=$(ps -ef | grep java | grep $APP_NAME | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        print_message "$GREEN" "✅ 服务运行中 (PID: $PID)"
        
        # 检查端口
        if netstat -tuln | grep -q ":$APP_PORT "; then
            print_message "$GREEN" "✅ 端口监听正常 ($APP_PORT)"
        else
            print_message "$RED" "❌ 端口未监听 ($APP_PORT)"
        fi
    else
        print_message "$RED" "❌ 服务未运行"
        return 1
    fi
}

# 主函数
main() {
    print_message "$GREEN" "========================================="
    print_message "$GREEN" "    若依后端部署脚本 v1.0"
    print_message "$GREEN" "========================================="
    echo ""
    
    # 检查依赖
    check_dependencies
    
    # 停止旧服务
    stop_old_service
    
    # 询问是否备份
    read -p "是否备份旧版本? (y/n, 默认: y): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        backup_old_version
    fi
    
    # 询问是否清理
    read -p "是否清理Maven缓存? (y/n, 默认: n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        clean_maven
    fi
    
    # 编译打包
    build_project
    
    # 启动服务
    start_service
    
    # 等待服务启动
    wait_for_service
    
    # 检查状态
    sleep 3
    check_status
    
    # 显示信息
    show_info
    
    # 询问是否查看日志
    read -p "是否查看启动日志? (y/n, 默认: y): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Nn]$ ]]; then
        view_logs
    fi
}

# 运行主函数
main "$@"

